"use strict"

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(err, conn) {
	if (err) return console.error('connect error ', err);
	conn.createChannel(function(err, ch) {
		if (err) return console.err('createChannel error ', err);

		var ex = 'rpc_exchange';
		var q_A2B = 'q_A2B';
		var key_A2B = 'key_A2B';

		var q_B2A = 'q_B2A'
		var key_B2A = 'key_B2A';
		ch.assertExchange(ex, 'topic', {
			durable: true
		});
		ch.prefetch(1);

		ch.assertQueue(q_A2B, {
			exclusive: false
		}, function(err, q1) {
			ch.assertQueue(q_B2A, {
				exclusive: false
			}, function(err, q2) {
				ch.bindQueue(q_A2B, ex, key_A2B);
				ch.bindQueue(q_B2A, ex, key_B2A);

				// a listen queue  q_B2A
				ch.consume(q_A2B, function(msg) {
					console.log(' [x] appB receive msg = %s', msg.content);
					ch.ack(msg);
					ch.publish(ex, key_B2A, new Buffer('echo:' + msg.content));
				}, {
					noAck: false
				});
			});
		})
	});
})